<template>
  <a-spin :spinning="loading" size="large">
    <van-form @submit="onSubmit" @failed="onFailed" ref="formRef">
      <h2>点位名称：{{ formDataList.name }}</h2>
      <div v-for="(k, i) in formDataList.forms">
        <h3>{{ i + 1 }}.表单名称：{{ k.name }}</h3>
        <h4>1.巡检项：</h4>
        <van-cell-group inset>
          <van-field 
          class="special"
          v-for="(item, index) in k.checkList"
          :label="item.name"
          :name="item.check">
            <template #input>
              <van-radio-group
              v-model="item.check"
              direction="horizontal"
              :disabled="isUpdate"
              @change="changeRadio(k)"
              >
                <van-radio name='NORMAL'>正常</van-radio>
                <van-radio name='ABNORMAL'>异常</van-radio>
              </van-radio-group>
            </template>
          </van-field>
        </van-cell-group>
        <h4>2.巡检描述</h4>
        <van-cell-group inset>
          <van-field
          v-for="(item, index) in k.textList"
          v-model="item.text"
          :label="item.name"
          :disabled="isUpdate"
          type="textarea"
          rows="2"
          autosize
          :placeholder="item.name">
          </van-field>
        </van-cell-group>
        <h4>3.巡检图片</h4>
        <div v-for="(item, index) in k.imageList">
          <h5>{{ item.name }}</h5>
          <van-cell-group inset >
            <van-uploader
            v-if="!isUpdate"
            :before-read="beforeRead"
            :max-size="800 * 1024"
            @oversize="onOversize"
            :after-read="afterRead"
            v-model="item.fileList"></van-uploader>
            <a-image :width="150" v-else v-for="url in item.fileList" :src="baseUrl + url"></a-image>
          </van-cell-group>          
        </div>
        <h4>4.巡检状态</h4>
        <van-cell-group inset>
          <van-field
          class="special"
          label="巡检状态">
            <template #input>
              <van-radio-group
              v-model="k.checkResult"
              :disabled="isUpdate"
              direction="horizontal">
                <van-radio name='NORMAL'>正常</van-radio>
                <van-radio name='ABNORMAL'>异常</van-radio>
              </van-radio-group>
            </template>
          </van-field>
        </van-cell-group>
        <h4 v-if="isUpdate">5.巡检人员：{{ k.inspectorName }}</h4>
        <h4 v-if="isUpdate">6.巡检时间：{{ k.createdTime }}</h4>
        <h4 v-if="handleRecordsList.length">(*).处理记录</h4>
        <van-cell-group inset v-for="item in handleRecordsList">
          <div class="handle">
            <span>处理人：{{ item.handlerName }}</span>
            <span>处理时间：{{ item.handleTime }}</span>
            <span>处理状态：{{ item.processStatus == 'PENDING' ? '处理中' : (item.processStatus == 'COMPLETED' ? '已处理' : '不需要处理') }}</span>
            <span>处理说明：{{ item.description }}</span>
            <span>
              处理图片：
              <a-image :width="150" v-for="url in item.afterImages" :src="baseUrl + url"></a-image>
            </span>
          </div>
        </van-cell-group>
        <h4 v-if="isUpdate" style="color: red;">7*.处理状态：</h4>
        <van-radio-group v-model="processStatus" :rules="[{required: true, message: '请选择处理结果'}]" v-if="isUpdate">
          <van-cell-group inset>
            <van-cell title="处理中">
              <template #right-icon>
                <van-radio name="PENDING" />
              </template>
            </van-cell>
            <van-cell title="已处理">
              <template #right-icon>
                <van-radio name="COMPLETED" />
              </template>
            </van-cell>
            <van-cell title="不需要处理">
              <template #right-icon>
                <van-radio name="NO_NEED" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
        <h4 v-if="isUpdate" style="color: red;">8*.处理说明：</h4>
        <van-cell-group inset v-if="isUpdate">
          <van-field
            v-model="description"
            type="textarea"
            rows="3"
            autosize
            placeholder="请输入处理说明"></van-field>        
        </van-cell-group>
        <h4 v-if="isUpdate" style="color: red;">9*.处理图片：</h4>
        <van-cell-group inset v-if="isUpdate">
          <van-uploader
          :before-read="beforeRead"
          :max-size="800 * 1024"
          @oversize="onOversize"
          :after-read="afterRead"
          v-model="afterImages"></van-uploader>
        </van-cell-group>
      </div>
      <br>
      <div class="btn">
        <van-button v-if="!isUpdate" type="primary" @click="doSubmit">提交</van-button>
        <van-button v-else type="success" @click="doSubmit">提交处理</van-button>
      </div>
    </van-form>
  </a-spin>
</template>

<script setup>
import { ref, onMounted, inject } from "vue"
import { Field as VanField, Form as VanForm, RadioGroup as VanRadioGroup, CellGroup as VanCellGroup, Uploader as VanUploader, Button as VanButton } from "vant";
import { useRoute } from "vue-router";
import router from "@/route/index.js";
import { photoUploadBase64, pointsForm, addRecords, formDetails, handleRecords } from "@/api/common.js";
import * as imageConversion from 'image-conversion'

const loading = ref(false),
  show = ref(false),
  toast = inject("toast"),
  route = useRoute(),
  formRef = ref(null),
  isUpdate = ref(false); //修改和详情
const formDataList = ref({});
// const baseUrl = ref("http://10.10.11.45:11000/uploads");
const baseUrl = ref("https://mobile.test.security.jxtvtech.com/portal/uploads/");
const processStatus = ref("PENDING");
const description = ref("");
const afterImages = ref([]);
const handleRecordsList = ref([]);

onMounted(() => {
  if(!!route.query.type && route.query.type == 'details') {
    isUpdate.value = true
    formDetails(route.query.recordId).then(res => {
      processStatus.value = res.processStatus
      handleRecordsList.value = res.handleRecords
      formDataList.value.name = res.pointName // 点位名称
      formDataList.value.forms = [res]
      formDataList.value.forms.forEach(item => {
        item.name = item.form.name // 表单名称
        item.textList = []
        item.checkList = []
        item.imageList = []
        item.itemRecords.forEach(k => {
          if(k.formItem.itemType == 'TEXT') {
            item.textList.push(k.formItem)
            k.formItem.text = k.values[0]
          }
          if(k.formItem.itemType == 'CHECK_STATUS') {
            item.checkList.push(k.formItem)
            k.formItem.check = k.values[0]
          }
          if(k.formItem.itemType == 'IMAGE_LIST') {
            item.imageList.push(k.formItem)
            k.formItem.fileList = k.values
          }
        })
      })
    })
  } else {
    pointsForm(route.query.qrCode).then(res => {
      formDataList.value = res
      formDataList.value.forms.forEach(item => {
        item.checkResult = 'NORMAL'
        item.textList = []
        item.checkList = []
        item.imageList = []
        item.items.forEach(k => {
          if(k.itemType == 'TEXT') {
            k.text = ""
            item.textList.push(k)
          }
          if(k.itemType == 'CHECK_STATUS') {
            k.check = 'NORMAL'
            item.checkList.push(k)
          }
          if(k.itemType == 'IMAGE_LIST') {
            k.fileList = []
            item.imageList.push(k)
          }
        })
      })
    })    
  }
})

function onOversize() {
  toast.error("文件大小不能超过800kb")
}

function onFailed(error) {
  console.log(error)
}

function doSubmit() {
  formRef.value.submit();
}

function onSubmit() {
  if(isUpdate.value) {
    loading.value = true
    let obj = {
      afterImages: [],
      description: description.value,
      processStatus: processStatus.value,
      recordId: route.query.recordId
    }
    afterImages.value.forEach(item => {
      obj.afterImages.push(item.fileName)
    })
    handleRecords(obj).then(res => {
      toast.success('创建成功！');
      loading.value = false;
      router.push('/home');
    }, err => {
      loading.value = false;
      toast.error(err.response.data.message)
    })
  } else {
    let tasks = []
    formDataList.value.forms.forEach(item => {
      let obj = {
        pointId: formDataList.value.id,
        formId: item.id,
        checkResult: item.checkResult,
        itemRecords: []
      }
      item.items.forEach(k => {
        if(k.itemType == 'TEXT') {
          obj.itemRecords.push({
            formItemId: k.id,
            values: [
              k.text
            ]
          })
        }
        if(k.itemType == 'CHECK_STATUS') {
          obj.itemRecords.push({
            formItemId: k.id,
            values: [
              k.check
            ]
          })
        }
        if(k.itemType == 'IMAGE_LIST') {
          obj.itemRecords.push({
            formItemId: k.id,
            values: (k.fileList.map(item => item.fileName))
          })
        }
      })
      tasks.push(obj)
    })
    runTasks(tasks);    
  }
}

async function asyncOperation(task) {
  return new Promise((resolve) => {
    loading.value = true
    addRecords(task).then(res => {
      resolve()
    })
  })
}

async function runTasks(tasks) {
  const promises = tasks.map(task => asyncOperation(task));
  await Promise.all(promises);
  toast.success('创建成功！');
  loading.value = false;
  router.go(-1);
}

function changeRadio(val) {
  let num = 0
  val.checkList.forEach(item => {
    if(item.check == 'ABNORMAL') {
      num ++
    }
  })
  if(num) {
    val.checkResult = 'ABNORMAL'
  } else {
    val.checkResult = 'NORMAL'
  }
}

function beforeRead(file) {
  return new Promise((resolve, reject) => {
    imageConversion.compressAccurately(file, 500).then(res => {
      res = new File([res], file.name, { type: res.type, lastModified: Date.now() })
      console.log('压缩后', res)
      resolve(res)
    })
  });
}

function afterRead(file) {
  uploadFile(file);
}
function uploadFile(file) {
  file.status = "uploading";
  loading.value = true;
  apiUpLoadImg(file);
}

function apiUpLoadImg(file) {
  var formData = new FormData();
  formData.append("file", file.file);
  if(isUpdate.value) {
    formData.append("type", "PROCESS_PHOTO")
  } else {
    formData.append("type", "RECORD_PHOTO")
  }
  //接口需要传的参数
  photoUploadBase64(formData).then(res => {
    file.status = "success";
    file.fileName = res
    loading.value = false;
  },err=>{
    loading.value = false
    alert(err)
  })
}
  
</script>

<style lang="less" scoped>
.handle {
  margin: 5px 20px;
  span {
    display: block;
  }
}
h5 {
  margin: 2px 22px;
}
h4 {
  font-weight: 400;
  margin: 2px 18px;
}
h3 {
  font-weight: 700;
  margin: 5px 12px;
}
h2 {
  font-weight: 700;
  margin: 3px 5px;
}
.special :deep(.van-field__label) {
  width: calc(100% - 150px);
}
:deep(.van-uploader) {
  margin: 8px 0 0 10px; 
}
.btn {
  margin: 0 16px;

  button {
    width: 100%;
    margin-bottom: 10px;
  }

}

:deep(.van-uploader__preview) {
  margin-right: 5px;
}

.home-title {

  margin-left: 15px;
  margin-top: 20px;

  h1 {
    font-weight: 700;
    margin: 0;
  }

  h3 {
    font-weight: 700;
    margin: 0;
    margin-left: 10px;
  }

  span {
    display: block;
    margin-left: 15px;
    margin-bottom: 3px;

    font.yellow {
      border: 1px solid #ffea00;
      color: #ffea00;
      padding: 1px 3px;
    }

    font.orange {
      border: 1px solid orange;
      color: orange;
      padding: 1px 3px;
    }

    font.red {
      border: 1px solid red;
      color: red;
      padding: 1px 3px;
    }

  }

}

:deep(.van-popup--bottom) {
  background-color: rgb(246, 247, 248);
}
</style>